#include "HttpServer.hpp"
#include <memory>
using namespace std;
using namespace server;

//http不用自己写客户端了，因为已经存在，直接使用浏览器就可以了
void Usage(std::string proc)
{
    cerr << "Usage:\n\t" << proc << " port\r\n\r\n";
}

std::string suffixToDesc(const std::string suffix)
{
    std::string ct = "Content-Type: ";
    if(suffix == ".html") ct += "text/html";
    else if(suffix == ".jpg") ct += "application/x-jpg";
    ct += "\r\n";
    return ct;
}

// 1. 服务器和网页分离
// 2. url -> / :web根目录
// 3. 我们要正确的给客户端返回资源类型，我们首先要自己知道，所有的资源都有后缀！
bool Get(const HttpRequest &req, HttpResponse &resp)
{
    if(req.path == "test.py")
    {
        //建立进程间通信, pipe
        //fork创建子进程，exec("/bin/python", test.py)
        //父进程，将req.parm 通过管道写给某些后端语言，py,java,php等语言
    }
    if(req.path == "/search")
    {
        //req.parm
        //使用我们自己写的C++的方法，提供服务
    }
    // for test
    cout << "--------------------------http start------------------------------" << endl;
    cout << req.inbuffer << endl;
    std::cout << "method: " << req.method << std::endl; 
    std::cout << "url: " << req.url << std::endl; 
    std::cout << "httpversion: " << req.httpversion << std::endl; 
    std::cout << "path: " << req.path << std::endl; 
    std::cout << "suffix: " << req.suffix << std::endl; 
    std::cout << "size: " << req.size << "字节" << std::endl; 
    cout << "--------------------------http end------------------------------" << endl;

    std::string respline = "Http/1.1 200 OK\r\n";
    std::string respheader = suffixToDesc(req.suffix);
    if(req.size > 0)
    {
        respheader += "Content-Length: ";
        respheader += std::to_string(req.size);
        respheader += "\r\n";
    }
    respheader += "location: https://www.qq.com/\r\n";
    std::string respblank = "\r\n";
    //std::string body = "<html lang=\"en\"><head><meta charset=\"UTF-8\"><title>for test</title><h1>hello world</h1></head><body><p>新华社北京6月1日电（记者阳娜、温竞华）我国首个国际科技组织总部集聚区5月31日在北京揭牌并正式启用。该集聚区由中国科协与北京市政府合作共建，首批已迎来国际动物学会、国际数字地球学会、国际氢能燃料电池协会等8家国际科技组织入驻。</p></body></html>";
    
    std::string body;
    if(!Util::readFile(req.path, &body))
    {
        Util::readFile(html_404, &body); // 一定能成功
    }

    resp.outbuffer += respline;
    resp.outbuffer += respheader;
    resp.outbuffer += respblank;
    resp.outbuffer += body;

    return true;
}


// ./httpServer 8080
int main(int argc, char* argv[])
{
    if(argc != 2)
    {
        Usage(argv[0]);
        exit(0);
    }

    uint16_t port = atoi(argv[1]);
    unique_ptr<HttpServer> httpsvr(new HttpServer(Get, port));

    // httpsvr->registerCb("/", Get);//功能路由！
    // httpsvr->registerCb("/search", Search);
    // httpsvr->registerCb("test.py", Other)
    httpsvr->initServer();
    httpsvr->start();
}

